<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/1/17
 * Time: 12:53
 */
namespace app\api\controller;

use app\api\model\MtUserInvoice;
use app\util\ReturnCode;

/**
 * 发票
 * Class Invoice
 * @package app\api\controller
 */
class Invoice extends Base
{
    /**
     * 提交发票申请
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function applyInvoice(){
        $rule = [
            "orderNo" => "require",
            "invoicType" =>"require|number|max:2",
            "rise" => "require|max:50",
            "riseType" => "require|number|max:2",
            "defaultRise" => "number",
            "userID" => "require|number",
        ];
        $msg = [];
        $data = $this->request->post();
        $verifiRes = (new Common())->VerifiString($rule, $msg, $data);
        if ($verifiRes['code'] == 2) {
            return $this->error(ReturnCode::EMPTY_PARAMS, $verifiRes['msg']);
        }
        $res = (new MtUserInvoice())->insertGetId($data,true);
        if(!$res){
            return $this->error(ReturnCode::DB_SAVE_ERROR,"入库失败");
        }
        if($data['defaultRise'] == 2){
            $default = (new MtUserInvoice())->where("defaultRise","2")->count();
            if($default){
                $res = (new MtUserInvoice())->where(["id","<>",$res])->update(["defaultRise"=>1]);
                if(!$res){
                    return $this->error(ReturnCode::DB_SAVE_ERROR,"设置默认抬头失败");
                }
            }
        }
        return $this->success("入库成功");
    }

    /**
     * 获取用户发票默认抬头
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getDefaultRise(){
        $userID = $this->request->param("userID");
        if(!$userID){
            return $this->error(ReturnCode::EMPTY_PARAMS,"缺少参数userID");
        }
        $defaultRise = (new MtUserInvoice())->where([["userID","=",$userID],["defaultRise","=","1"]])->find();
        if(!$defaultRise){
            return $this->error(ReturnCode::DB_READ_ERROR,"查询失败");
        }
        return $this->success("查询成功",$defaultRise);
    }
}